package com.demo.forum.controller;

import com.demo.forum.common.Result;
import com.demo.forum.common.ResultCode;
import com.demo.forum.config.AppConfig;
import com.demo.forum.model.User;
import com.demo.forum.model.exception.ApplicationException;
import com.demo.forum.services.impl.UserServiceImpl;
import com.demo.forum.utils.MD5Utils;
import com.demo.forum.utils.StringUtil;
import com.demo.forum.utils.UUIDUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@Slf4j
@RequestMapping("/user")
@Api(tags = "用户接口")
public class UserController {


    @Autowired
    private UserServiceImpl userService;

    @PostMapping("/register")
    @ApiOperation("用户注册接口")
    public Result register(@RequestParam("username") @NonNull @ApiParam("用户名") String username,
                           @RequestParam("password") @NonNull @ApiParam("密码") String password,
                           @RequestParam("passwordRepeat") @NonNull @ApiParam("确认密码") String passwordRepeat,
                           @RequestParam("nickname") @NonNull @ApiParam("昵称") String nickname
    ) {
        if (!password.equals(passwordRepeat)) {
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            throw new ApplicationException(Result.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME));
        }

        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);
        String salt
                = UUIDUtil.UUID_32();
        user.setSalt(salt);
        String cr = MD5Utils.md5Salt(password, salt);
        user.setPassword(cr);
        userService.createNormalUser(user);
        return Result.success();

    }

    @ApiOperation("用户登录")
    @PostMapping("/login")
    public Result login(HttpServletRequest request, @ApiParam("用户名") @RequestParam("username") @NonNull String username,
                        @ApiParam("密码") @RequestParam("password") @NonNull String password) {
        User user = userService.login(username, password);
        if (user == null) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(Result.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        HttpSession session = request.getSession(true);
        session.setAttribute(AppConfig.USER_LOGUN, user);

        return Result.success();


    }


    @ApiOperation("获取用户信息")
    @GetMapping("/info")
    public Result<User> getUserInfo(HttpServletRequest request,
                                    @ApiParam("用户id") @RequestParam(value = "id", required = false) Long id) {

        User user = null;
        if (id == null) {
            //从session 中获取用户信息
            HttpSession session = request.getSession(false);
            user = (User) session.getAttribute(AppConfig.USER_LOGUN);
        } else {
            user = userService.selectById(id);

        }
        if (user == null) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(Result.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        log.info("来到用户详情也");
        return Result.success(user);
    }

    @ApiOperation("用户退出")
    @GetMapping("/logout")

    public Result logout(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            log.info("退出成功");
            session.invalidate();
        }
        return Result.success("退出成功!");

    }

    /**
     * 修改个人信息
     *
     * @param username 用户名
     * @param nickname 昵称
     * @param gender   性别
     * @param email    邮箱
     * @param phoneNum 电话号
     * @param remark   个人简介
     * @return AppResult
     */
    @ApiOperation("修改个人信息")
    @PostMapping("/modifyInfo")
    public Result modifyInfo(HttpServletRequest request,
                             @ApiParam("用户名") @RequestParam(value = "username", required = false) String username,
                             @ApiParam("昵称") @RequestParam(value = "nickname", required = false) String nickname,
                             @ApiParam("性别") @RequestParam(value = "gender", required = false) Byte gender,
                             @ApiParam("邮箱") @RequestParam(value = "email", required = false) String email,
                             @ApiParam("电话号") @RequestParam(value = "phoneNum", required = false) String phoneNum,
                             @ApiParam("个人简介") @RequestParam(value = "remark", required = false) String remark) {

        if (StringUtil.isEmpty(username) && StringUtil.isEmpty(nickname) && StringUtil.isEmpty(email)
                && StringUtil.isEmpty(phoneNum) && StringUtil.isEmpty(remark) && gender == null) {
            return Result.failed("请输入内容!");
        }
        //从session 中获取用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_LOGUN);
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setUsername(username);
        updateUser.setNickname(nickname);
        updateUser.setEmail(email);
        updateUser.setPhoneNum(phoneNum);
        updateUser.setRemark(remark);
        updateUser.setGender(gender);

        userService.modifyInfo(updateUser);
        //更新session
        User newUser = userService.selectById(user.getId());
        session.setAttribute(AppConfig.USER_LOGUN, newUser);
        return Result.success(newUser);
    }

    @ApiOperation("修改密码")
    @PostMapping("/modifyPwd")
    public Result modifyPassword(HttpServletRequest request,
                                 @ApiParam("原密码") @RequestParam("oldPassword") @NonNull String oldPassword,
                                 @ApiParam("新密码") @RequestParam("newPassword") @NonNull String newPassword,
                                 @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {

        //密码 与 确认密码是否相同
        if (!newPassword.equalsIgnoreCase(passwordRepeat)) {
            return Result.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        //获取用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_LOGUN);
        if (user.getDeleteState() == 1) {
            return Result.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        userService.modifyPassword(user.getId(), newPassword, oldPassword);
       if(session!=null){
           session.invalidate();
       }
        return Result.success();


    }
}
